<template>
  <movable-area class="drag-sort" :style="{height: currentListLength + 'px'}" id="drag">
    <movable-view
        v-for="(item, index) in currentList"
        :key="item.name"
        :x="0"
        :y="item.y"
        direction="vertical"
        damping="50"
        :disabled="cantMove"
        :animation="active !== index"
        @touchstart="touchstart"
        @touchmove="touchmove"
        @touchend="touchend"
        class="drag-sort-item"
        :style="{height: height+'px'}"
        :class="{'active': active === index}" @click="itemClick(item)">
      <slot :item="item" :delClick="delClick"></slot>
    </movable-view>
  </movable-area>
</template>

<script>
export default {
  name: 'drag-sort',

  data() {
    return {
      height: 60, // 高度
      currentList: [],
      active: -1, // 当前激活的item
      itemIndex: 0, // 当前激活的item的原index
      topY: 0, // 距离顶部的距离
      deviationY: 0, // 偏移量
      cantMove: true, // 是否禁止拖动
      pressTimer: null
    }
  },
  computed: {
    currentListLength() {
      return this.currentList.length * this.height
    }
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    list(val) {
      this.onUpdateCurrentList()
    },
    disabled(newVal, oldVal) {
      // 这里可以实现当 disabled 变化时需要执行的逻辑
      if (oldVal == true && newVal == false) {
        // 当 disabled 变为 true 时，返回 currentList
        this.$emit('complete', this.currentList);
      }
    }
  },
  created() {
    this.onUpdateCurrentList()
  },
  mounted() {
  },
  updated() {
  },
  filters: {},
  methods: {
    itemClick(item) {
      this.$emit('childClick', item);
    },
    delClick(item) {
      this.$emit('delclick', item);
    },
    onUpdateCurrentList() {
      this.currentList = this.list.map((item, index) => ({
        ...item,
        index,
        y: index * this.height,
        animation: true
      }));
    },
    touchstart(e) {
      console.log(1111)
      if (!this.disabled) {
        return;
      }
      this.pressTimer = setTimeout(() => {
        this.cantMove = false;
        // 计算y轴点击位置
        var query = uni.createSelectorQuery().in(this);
        query.select('#drag').boundingClientRect();
        query.exec((res) => {
          this.topY = res[0].top
          let touchY = e.mp.touches[0].clientY - res[0].top
          this.deviationY = touchY % this.height
          // console.log(touchY)
          for (const key in this.currentList) {
            if ((this.currentList[key].index * this.height < touchY) && ((this.currentList[key].index + 1) * this.height > touchY)) {
              this.active = Number(key)
              this.itemIndex = this.currentList[key].index
              break
            }
          }
        });
      }, 500);

    },
    touchmove(e) {
      if (!this.disabled && !this.cantMove) {
        return;
      }
      clearTimeout(this.pressTimer);
      if (this.active < 0) return
      let touchY = (e.mp.touches[0].clientY - this.topY) - this.deviationY
      // console.log(touchY)
      this.currentList[this.active].y = touchY
      for (const key in this.currentList) {
        // 跳过当前操作的item
        if (this.currentList[key].index !== this.currentList[this.active].index) {
          if (this.currentList[key].index > this.currentList[this.active].index) {
            if (touchY > this.currentList[key].index * this.height - this.height / 2) {
              this.currentList[this.active].index = this.currentList[key].index
              this.currentList[key].index = this.currentList[key].index - 1
              this.currentList[key].y = this.currentList[key].index * this.height
              this.vibrate()
              break
            }
          } else {
            if (touchY < this.currentList[key].index * this.height + this.height / 2) {
              this.currentList[this.active].index = this.currentList[key].index
              this.currentList[key].index = this.currentList[key].index + 1
              this.currentList[key].y = this.currentList[key].index * this.height
              this.vibrate()
              break
            }
          }
        }
      }
    },
    //兼容微信小程序震动
    vibrate() {
      uni.vibrateShort()
    },
    touchend(e) {
      console.log(2222)
      if (!this.disabled) {
        return;
      }
      clearTimeout(this.pressTimer);
      if (!this.cantMove) {
        this.cantMove = true;
        if ((this.itemIndex !== this.currentList[this.active].index) && (this.active > -1)) {
          // 记录活动元素的原始位置
          this.$emit('change', {
            // 操作值
            data: (() => {
              let data = {
                ...this.currentList[this.active]
              };
              delete data.index;
              delete data.y;
              delete data.animation;
              return data;
            })(),
            // 插队的位置前面的值
            frontData: (() => {
              for (const iterator of this.currentList) {
                if (this.currentList[this.active].index - 1 === iterator.index) {
                  let data = {
                    ...iterator
                  };
                  delete data.index;
                  delete data.y;
                  delete data.animation;
                  return data;
                }
              }
            })(),
            // 增加原来的位置和最终位置
            originalPosition: this.itemIndex,
            finalPosition: this.currentList[this.active].index
          });
        }

        this.currentList[this.active].animation = true;
        this.currentList[this.active].y = this.currentList[this.active].index * this.height;
        this.active = -1;
      }
    }
  }
}
</script>

<style lang='less' scoped>
@import "~./1px.less";

.drag-sort {
  width: 100%;
  background-color: white;
  border-radius: 50rpx;
}

.drag-sort-item:nth-child(2) {
  border-radius: 50rpx 50rpx 0 0;
}

.drag-sort-item:last-child {
  border-radius: 0 0 50rpx 50rpx;
}

.drag-sort-item {
  position: absolute !important;
  display: flex;
  width: 100%;
  background-color: rgba(255, 255, 255, 0);

  &:active {
    transition: background-color 0.25s;
    background-color: #f0f0f0; // 高亮背景色
  }
}

.touch {
  height: 100%;
  width: 100rpx;
}

.active {
  //box-shadow: 0 0 40rpx #DDDDDD;
  z-index: 99;
  border-radius: 50rpx !important;
  background-color: #f0f0f0;
}
</style>
